package com.example.rbacmanage.util;

import jakarta.servlet.http.HttpServletResponse;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;

public class FileUtils {
    public static File multipartFileToFile(MultipartFile multipartFile) {
        String path = multipartFile.getOriginalFilename();
        File file = new File(path);
        try{
            if (!file.exists()) {
                file.createNewFile();
            }
            file.deleteOnExit();
            FileCopyUtils.copy(multipartFile.getBytes(),file);
        }catch (Exception e){
            e.printStackTrace();
        }
        return file;
    }

    public static void downloadFile(HttpServletResponse response, File file) {
        FileInputStream fis = null;
        BufferedInputStream bis = null;
        try{
            if (file.exists()) {
                response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
                byte[] buffer = new byte[1024];
                fis = new FileInputStream(file);
                bis = new BufferedInputStream(fis);
                OutputStream os = response.getOutputStream();
                int i = bis.read(buffer);
                while (i != -1) {
                    os.write(buffer, 0, i);
                    i = bis.read(buffer);
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if (bis != null){
                try {
                    bis.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }

        }
    }


    public static MultipartFile convert(String base64String, String originalFilename){
        try{
            // 解码Base64字符串为字节数组
            byte[] decodedBytes = java.util.Base64.getDecoder().decode(base64String);

            // 创建临时文件
            Path tempFile = Files.createTempFile("upload-", ".jpeg");

            // 将字节数组写入临时文件
            Files.write(tempFile, decodedBytes);

            // 读取临时文件内容并封装为MockMultipartFile
            File file = tempFile.toFile();
            file.deleteOnExit();
            return new MockMultipartFile(
                    "file",
                    originalFilename,
                    null,
                    new ByteArrayInputStream(decodedBytes)
            );
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }
}
